package org.smile.validate.rule;

import org.smile.commons.Strings;
import org.smile.util.StringUtils;
import org.smile.validate.CustomValidator;
import org.smile.validate.Field;
import org.smile.validate.ValidateType;

public class FiledValidateRule extends AbstractRule{
	/**配置验证规则的注解*/
	protected Field f;
	//不存在key时使用替换品
	protected String fakeKey;
	/**属性名称*/
	protected String property;

	protected String fieldName;
	
	public FiledValidateRule(Field f){
		this.f=f;
		this.fakeKey=this.f.name();
	}

	public FiledValidateRule(String prefix,Field f){
		this.f=f;
		this.fakeKey=prefix.endsWith(Strings.DOT)?prefix+this.f.name():prefix+Strings.DOT+f.name();
	}

	
	@Override
	public String getFieldName() {
		if(this.fieldName!=null){
			return this.fieldName;
		}
		if(this.property==null){
			return f.name();
		}else{
			if(StringUtils.isEmpty(f.name())){
				return this.property==null?Strings.BLANK:this.property;
			}else{
				return this.property+Strings.DOT+f.name();
			}
		}
	}

	@Override
	public void setFieldName(String fieldName) {
		this.fieldName=fieldName;
	}

	@Override
	public ValidateType getType() {
		return f.type();
	}

	@Override
	public Comparable[] getRange() {
		String[] r=f.range();
		if(f.type()==ValidateType.lengthRange){
			Integer[] range=new Integer[0];
			range[0]=Integer.parseInt(r[0]);
			range[1]=Integer.parseInt(r[1]);
			return range;
		}
		return f.range();
	}

	@Override
	public Object getValue() {
		return f.value();
	}

	@Override
	public String getRegexp() {
		return f.regexp();
	}

	@Override
	public String getText() {
		return f.text();
	}

	@Override
	public String getKey() {
		return f.key();
	}

	@Override
	public String getKeyWhenNull() {
		return this.fakeKey;
	}

	@Override
	public Class<? extends CustomValidator> getCustom() {
		return f.custom();
	}

	@Override
	public boolean ifnull() {
		return f.ifnull();
	}

	public void setProperty(String property) {
		this.property = property;
	}
}
